package com.example.demo.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Map;
import java.util.Properties;

@Configuration
public class MailSenderConfig {

    @ConfigurationProperties("mail.account.default")
    @Bean
    public MailAccountConfig defaultMailAccountConfig() {
        return new MailAccountConfig();
    }

    @ConfigurationProperties("mail.account.special")
    @Bean
    public MailAccountConfig specialMailAccountConfig() {
        return new MailAccountConfig();
    }

    @ConfigurationProperties("mail.server.netease")
    @Bean
    public MailServerConfig netease() {
        return new MailServerConfig();
    }

    @ConfigurationProperties("mail.server.outlook")
    @Bean
    public MailServerConfig outlook() {
        return new MailServerConfig();
    }

    @Bean("defaultMailSender")
    public JavaMailSenderImpl defaultMailSender(
            MailAccountConfig defaultMailAccountConfig, Map<String, MailServerConfig> map) {
        return getJavaMailSender(defaultMailAccountConfig, map);
    }

    @Bean("specialMailSender")
    public JavaMailSenderImpl specialMailSender(
            MailAccountConfig specialMailAccountConfig, Map<String, MailServerConfig> map) {
        return getJavaMailSender(specialMailAccountConfig, map);
    }

    private JavaMailSenderImpl getJavaMailSender(MailAccountConfig accountConfig, Map<String, MailServerConfig> map) {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();

        // 根据账号类型找到服务器配置
        MailServerConfig mailServerConfig = map.get(accountConfig.getType());
        // 发邮件使用smtp服务器
        MailServerConfig.Protocol protocol = mailServerConfig.getHost().get("smtp");
        javaMailSender.setHost(protocol.getHost());
        // 使用非SSL协议端口
        javaMailSender.setPort(Integer.parseInt(protocol.getPort()));
        javaMailSender.setProtocol("smtp");
        javaMailSender.setUsername(accountConfig.getUsername());
        javaMailSender.setPassword(accountConfig.getPassword());
        javaMailSender.setDefaultEncoding("UTF-8");
        Properties props = new Properties();
        props.putAll(mailServerConfig.getProperties());
        javaMailSender.setJavaMailProperties(props);
        return javaMailSender;
    }

}
